//******************************COPYRIGHT NOTICE*******************************
//All rights reserved.  This material is confidential and proprietary to 
//CogentSoft (Shen Zhen) Limited and no part of this material should be reproduced, 
//published in any form by any means, electronic or mechanical including
//photocopy or any information storage or retrieval system nor should the
//material be disclosed to third parties without the express written 
//authorization of CogentSoft (Shen Zhen) Limited.
/*
 <PRE>
 * **************************VSS GENERATED VERSION NUMBER************************
 * $Revision: $
 * ******************************PROGRAM DESCRIPTION*****************************
 * Program Name   : ParamUtils.java
 * Description: ParamUtils object
 * Creation Date  : 2006-4-19
 * Creator: ϵͳ��
 * ******************************MODIFICATION HISTORY****************************
 * Modify Date: [Date in YYYY/MM/DD]
 * Modifier   : [Developer Name]
 * CR / SIR No.   : [Cogent��s CR / SIR No.]
 * Description: [Description]
 * ******************************************************************************
 </PRE>
 */

/**
 * ParamUtils object
 * 
 * <DT><B>Copyright:</B>
 * <DD>The contents of this file are confidential and proprietary to Cogent.</DD>
 * <DD>Copying is explicitly prohibited without the express permission of Cogent.</DD>
 * 
 * @author LQ
 * @version 1.0
 *
 */
package com.cogent.common.util;

import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;

@SuppressWarnings("unchecked")
public class ParamUtils {
    
    /**
     * 返回Long 对象，不为空，取不到时为Long(0)
     * @param request
     * @param name
     * @return
     */
    public static Long getLong(HttpServletRequest request, String name) {
        return getLong(request, name, false);
    }
    
    /**
     * @param request
     * @param name
     * @param isNull
     * @return
     */
    public static Long getLong(HttpServletRequest request, String name, boolean isNull) {
        Long result = null;
        String str = request.getParameter(name);
        if (isNull && str == null)
            return null;
        try {
            //result = Integer.parseInt(str);
            result = Long.valueOf(str);
        } catch (Exception e) {
            //do nothing, just ignore this
        }
        return result;
    }
    
    /**
     * 获取Long请求参数,为null时返回值为defaultValue的Long对象.
     * @param request
     * @param name
     * @param defaultValue
     * @return
     * @author  Sunm
     * @since   2008-06-02
     */
    public static Long getLong(HttpServletRequest request, String name, int defaultValue) {
        Long value = getLong(request,name);
        if(value==null)
            return Long.valueOf(defaultValue);
        return value;
    }
    
    /**
     * not return null, return Integer(0) instead
     * @param request
     * @param name
     * @return
     */
    public static Integer getInteger(HttpServletRequest request, String name) {
        return getInteger(request, name, false);
    }
    
    /**
     * @param request
     * @param name
     * @param isNull
     * @return
     */
    public static Integer getInteger(HttpServletRequest request, String name, boolean isNull) {
        int result = 0;
        String str = request.getParameter(name);
        if (isNull && str == null)
            return null;
        try {
            result = Integer.parseInt(str);
        } catch (Exception e) {
            //do nothing, just ignore this
        }
        return new Integer(result);
    }
    
    /**
     * 获取整形参数,出现异常时返回defaultValue.
     * @param request
     * @param name
     * @return
     */
    public static int getInt(HttpServletRequest request, String name, int defaultValue) {
    	int result = 0;
        String str = request.getParameter(name);
        try {
            result = Integer.parseInt(str);
        } catch (Exception e) {
            result = defaultValue;
        }
        return result;
    }
    
    public static int getInt(HttpServletRequest request, String name) {
        return getInt(request, name, 0);
    }
    
    /**
     * 获取指定参数的值.
     * 若为null，则返回"".
     * 返回的字符串经过trim()处理.
     * @param request
     * @param parameter 参数名.
     * @return String
     */
    public static String getString(HttpServletRequest request, String parameter) {
        String str = request.getParameter(parameter);
        if (str == null) {
            return "";
        } else {
            return str.trim();
        }
    }
    
    /*
    * @return null 
    */
   public static String getNull(String str) {
       if (str == null) {
           return "";
       } else {
           return str.trim();
       }
   }    
    
    
    /**
     * 通过转码获取指定参数的值.
     * 转码由"ISO8859_1"转为"UTF-8"
     * 若配置了由web服务器处理编码，则不进行编码转换.
     * 为null时返回""
     * @param request
     * @param parameter 参数名.
     * @return 转码后的UTF-8字符串.
     */
    public static String getStringToUTF8(HttpServletRequest request, String parameter) {
        String str = request.getParameter(parameter);
        if (str == null || str.trim().equals("")) {
            return "";
        } else {
        	str = str.trim();
        	String webApp = Globals.getProperty("webapp");
        	if (webApp == null || webApp.trim().equals("")) {
	            try {
	                str = new String(str.getBytes("ISO8859_1"), "UTF-8");
	            } catch (Exception e) {
	                throw new RuntimeException(e);
	            }
        	}
            return str;
        }
    }
    
	/**
	 * Gets a parameter as a string.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @return The value of the parameter or null if the parameter was not found
	 *         or if the parameter is a zero-length string.
	 */
	public static String getParameter(HttpServletRequest request, String name) {
		return getParameter(request, name, false);
	}

	public static String[] getParameters(HttpServletRequest request, String name) {
		return request.getParameterValues(name);
	}

	/**
	 * Gets a parameter as a string.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @param emptyStringsOK
	 *            Return the parameter values even if it is an empty string.
	 * @return The value of the parameter or null if the parameter was not
	 *         found.
	 */
	public static String getParameter(HttpServletRequest request, String name,
			boolean emptyToNull) {
		String temp = request.getParameter(name);
		if (temp != null) {
			temp = temp.trim();
			if (temp.equals("") && emptyToNull) {
				return null;
			} else {
				return temp;
			}
		} else {
			return null;
		}
	}

	public static String getParameter(HttpServletRequest request, String name,
			String defaultString) {
		String temp = request.getParameter(name);
		if (temp != null) {
			return temp.trim();
		} else {
			return defaultString;
		}
	}

	/**
	 * Gets a parameter as a boolean.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @return True if the value of the parameter was "true", false otherwise.
	 */
	public static boolean getBooleanParameter(HttpServletRequest request,
			String name) {
		return getBooleanParameter(request, name, false);
	}

	/**
	 * Gets a parameter as a boolean.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @return True if the value of the parameter was "true", false otherwise.
	 */
	public static boolean getBooleanParameter(HttpServletRequest request,
			String name, boolean defaultVal) {
		String temp = request.getParameter(name);
		if ("true".equals(temp) || "on".equals(temp)) {
			return true;
		} else if ("false".equals(temp) || "off".equals(temp)) {
			return false;
		} else {
			return defaultVal;
		}
	}

	/**
	 * Gets a parameter as an int.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @return The int value of the parameter specified or the default value if
	 *         the parameter is not found.
	 */
	public static int getIntParameter(HttpServletRequest request, String name,
			int defaultNum) {
		String temp = request.getParameter(name);
		if (temp != null && !temp.equals("")) {
			int num = defaultNum;
			try {
				num = Integer.parseInt(temp);
			} catch (Exception ignored) {
			}
			return num;
		} else {
			return defaultNum;
		}
	}

	/**
	 * Gets a list of int parameters.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @param defaultNum
	 *            The default value of a parameter, if the parameter can't be
	 *            converted into an int.
	 */
	public static int[] getIntParameters(HttpServletRequest request,
			String name, int defaultNum) {
		String[] paramValues = request.getParameterValues(name);
		if (paramValues == null) {
			return null;
		}
		if (paramValues.length < 1) {
			return new int[0];
		}
		int[] values = new int[paramValues.length];
		for (int i = 0; i < paramValues.length; i++) {
			try {
				values[i] = Integer.parseInt(paramValues[i]);
			} catch (Exception e) {
				values[i] = defaultNum;
			}
		}
		return values;
	}

	/**
	 * Gets a parameter as an int.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @return The int value of the parameter specified or the default value if
	 *         the parameter is not found.
	 */
	public static short getShortParameter(HttpServletRequest request,
			String name, short defaultShort) {
		String temp = request.getParameter(name);
		if (temp != null && !temp.equals("")) {
			short s = defaultShort;
			try {
				s = Short.parseShort(temp);
			} catch (Exception ignored) {
			}
			return s;
		} else {
			return defaultShort;
		}
	}

	/**
	 * Gets a list of int parameters.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @param defaultNum
	 *            The default value of a parameter, if the parameter can't be
	 *            converted into an int.
	 */
	public static short[] getShortParameters(HttpServletRequest request,
			String name, short defaultShort) {
		String[] paramValues = request.getParameterValues(name);
		if (paramValues == null) {
			return null;
		}
		if (paramValues.length < 1) {
			return new short[0];
		}
		short[] values = new short[paramValues.length];
		for (int i = 0; i < paramValues.length; i++) {
			try {
				values[i] = Short.parseShort(paramValues[i]);
			} catch (Exception e) {
				values[i] = defaultShort;
			}
		}
		return values;
	}

	/**
	 * Gets a parameter as a double.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @return The double value of the parameter specified or the default value
	 *         if the parameter is not found.
	 */
	public static double getDoubleParameter(HttpServletRequest request,
			String name, double defaultNum) {
		String temp = request.getParameter(name);
		if (temp != null && !temp.equals("")) {
			double num = defaultNum;
			try {
				num = Double.parseDouble(temp);
			} catch (Exception ignored) {
			}
			return num;
		} else {
			return defaultNum;
		}
	}

	/**
	 * Gets a parameter as a long.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @return The long value of the parameter specified or the default value if
	 *         the parameter is not found.
	 */
	public static long getLongParameter(HttpServletRequest request,
			String name, long defaultNum) {
		String temp = request.getParameter(name);
		if (temp != null && !temp.equals("")) {
			long num = defaultNum;
			try {
				num = Long.parseLong(temp);
			} catch (Exception ignored) {
			}
			return num;
		} else {
			return defaultNum;
		}
	}

	/**
	 * Gets a list of long parameters.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @param defaultNum
	 *            The default value of a parameter, if the parameter can't be
	 *            converted into a long.
	 */
	public static long[] getLongParameters(HttpServletRequest request,
			String name, long defaultNum) {
		String[] paramValues = request.getParameterValues(name);
		if (paramValues == null) {
			return null;
		}
		if (paramValues.length < 1) {
			return new long[0];
		}
		long[] values = new long[paramValues.length];
		for (int i = 0; i < paramValues.length; i++) {
			try {
				values[i] = Long.parseLong(paramValues[i]);
			} catch (Exception e) {
				values[i] = defaultNum;
			}
		}
		return values;
	}
	
	public static Long[] getParamsAsLong(HttpServletRequest request, String name, long defaultNum){
		String[] paramValues = request.getParameterValues(name);
		if (paramValues == null) {
			return null;
		}
		if (paramValues.length < 1) {
			return new Long[0];
		}
		Long[] values = new Long[paramValues.length];
		for (int i = 0; i < paramValues.length; i++) {
			try {
				values[i] = new Long(paramValues[i]);
			} catch (Exception e) {
				values[i] = new Long(defaultNum);
			}
		}
		return values;
		
	}

	/**
	 * Gets a BigDecimal as parameters.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @param defaultNum
	 *            The default value of a parameter, if the parameter can't be
	 *            converted into a long.
	 */
	public static BigDecimal getBigDecimalParameter(HttpServletRequest request,
			String name, BigDecimal defaultNum) {
		String temp = request.getParameter(name);
		if (temp != null && !temp.equals("")) {
			BigDecimal num = defaultNum;
			try {
				num = new BigDecimal(temp);
			} catch (Exception ignored) {
			}
			return num;
		} else {
			return defaultNum;
		}
	}

	/**
	 * Gets a parameter as a string.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @return The value of the parameter or null if the parameter was not found
	 *         or if the parameter is a zero-length string.
	 */
	public static String getAttribute(HttpServletRequest request, String name) {
		return getAttribute(request, name, false);
	}

	/**
	 * Gets a parameter as a string.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the parameter you want to get
	 * @param emptyStringsOK
	 *            Return the parameter values even if it is an empty string.
	 * @return The value of the parameter or null if the parameter was not
	 *         found.
	 */
	public static String getAttribute(HttpServletRequest request, String name,
			boolean emptyStringsOK) {
		String temp = (String) request.getAttribute(name);
		if (temp != null) {
			if (temp.equals("") && !emptyStringsOK) {
				return null;
			} else {
				return temp;
			}
		} else {
			return null;
		}
	}

	/**
	 * Gets an attribute as a boolean.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the attribute you want to get
	 * @return True if the value of the attribute is "true", false otherwise.
	 */
	public static boolean getBooleanAttribute(HttpServletRequest request,
			String name) {
		String temp = (String) request.getAttribute(name);
		if (temp != null && temp.equals("true")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Gets an attribute as a boolean.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the attribute you want to get
	 * @return True if the value of the attribute is "true", false otherwise.
	 */
	public static String getStringAttribute(HttpServletRequest request,String name) {
		String temp = (String) request.getAttribute(name);
		if (temp != null) {
			return temp;
		} else {
			return "";
		}
	}

	/**
	 * 当请求存在某个属性时，显示返回标记和名称
	 * 使用时，请参考gatherFamilyModIpt.jsp
	 * @param request
	 * @param name
	 * @param separator
	 * @return
	 */
	public static String getMark(HttpServletRequest request,String name,String separator) {
		String temp = getStringAttribute(request,name);
		if(!HtmlUtil.isEmpty(temp)) {
			if(!HtmlUtil.isEmpty(separator)) {
				return "★" + separator;
			}
			return "★";
		}
		return "";
	}

	/**
	 * 当请求存在某个属性时，显示返回标记和名称
	 * 使用时，请参考gatherFamilyModIpt.jsp
	 * @param request
	 * @param name
	 * @return
	 */
	public static String getMark(HttpServletRequest request,String name) {
		return getMark(request,name,"");
	}
	
	/**
	 * Gets an attribute as a int.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the attribute you want to get
	 * @return The int value of the attribute or the default value if the
	 *         attribute is not found or is a zero length string.
	 */
	public static int getIntAttribute(HttpServletRequest request, String name,
			int defaultNum) {
		String temp = (String) request.getAttribute(name);
		if (temp != null && !temp.equals("")) {
			int num = defaultNum;
			try {
				num = Integer.parseInt(temp);
			} catch (Exception ignored) {
			}
			return num;
		} else {
			return defaultNum;
		}
	}

	/**
	 * Gets an attribute as a long.
	 * 
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param name
	 *            The name of the attribute you want to get
	 * @return The long value of the attribute or the default value if the
	 *         attribute is not found or is a zero length string.
	 */
	public static long getLongAttribute(HttpServletRequest request,
			String name, long defaultNum) {
		String temp = (String) request.getAttribute(name);
		if (temp != null && !temp.equals("")) {
			long num = defaultNum;
			try {
				num = Long.parseLong(temp);
			} catch (Exception ignored) {
			}
			return num;
		} else {
			return defaultNum;
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param name
	 * @param defaultNum
	 * @return
	 */
	public static Long getParamAsLong(HttpServletRequest request, String name, long defaultNum){
		return new Long(getLongParameter(request,name,defaultNum));
	}

    /**
     * 确定Action中的操作不需要校验ActionForm
     * @param request   请求
     * @return  请求中的method参数值以"list"、"add"、"view"、"mod"或"resume"开头则返回true
     */
    public static boolean isMethodOutOfValidator(HttpServletRequest request) {
        String methodName = request.getParameter("method");
        if(HtmlUtil.isEmpty(methodName))    return false;
        return methodName.startsWith("list")
                || methodName.startsWith("add")
                || methodName.startsWith("view")
                || methodName.startsWith("mod")
                || methodName.startsWith("del")
                || methodName.startsWith("recycle")
                || methodName.startsWith("aud")
                || methodName.startsWith("load")
                || methodName.startsWith("home")
                || methodName.startsWith("resume")
                || methodName.startsWith("export")
                || methodName.startsWith("search")
                || methodName.startsWith("set")
                || methodName.startsWith("print")
                || methodName.startsWith("show");
        
    }
    
    /**
     * 确定Action中的操作方法将修改记录
     * @param request   请求
     * @return  请求中的method参数值以"save"、"update"、"recycle"、"delete"或"resume"开头则返回true
     */
    public static boolean isMethodChangeData(HttpServletRequest request) {
        String methodName = request.getParameter("method");
        if(HtmlUtil.isEmpty(methodName))    return false;
        //add zouow 2008-02-27 用户管理 初始化密码时 不处理清除缓存
        if("resetPwd".equals(methodName))    return false;
        return methodName.startsWith("save") || 
                methodName.startsWith("update") ||
                methodName.startsWith("recycle") ||
                methodName.startsWith("reset") ||
                methodName.startsWith("delete") ||
                methodName.startsWith("resume");
    }
    
    /**
     * 获取Action的名称
     * @param request   请求
     * @return  如Action的名称为/organ.do，则此方法将返回organ
     */
    public static String getActionName(HttpServletRequest request) {
        String dispatchPath = request.getRequestURI();
        String actionName = dispatchPath.substring(dispatchPath.lastIndexOf("/")+1, dispatchPath.lastIndexOf("."));
        return actionName;
    }
    
    /**
     * 确定action中的method参数值与关键字符相同
     * @param request   请求
     * @param methodName    关键字符，即方法名称
     * @return
     */
    public static boolean isMatchMethodName(HttpServletRequest request,String methodName) {
        if(methodName==null)    return false;
        String method = request.getParameter("method");
        return methodName.equalsIgnoreCase(method);
    }
    
    /**
     * 确定字符数组包含关键字符
     * @param str   关键字符
     * @param arr   字符数组
     * @return
     */
    public static boolean isInArr(String str,String[] arr){
        if(arr==null || HtmlUtil.isEmpty(str)) return false;
        for(int i=0;i<arr.length;i++){
          String tmpStr = arr[i];
          if(str.equalsIgnoreCase(tmpStr)){
            return true;
          }
        }
        return false;
     }
}

/*
 * *****************************VSS GENERATED
 * HISTORY***************************** $History: $
 * *******************************************************************************
 */